package com.kele.controller;

import com.kele.domain.User;
import com.kele.service.FileService;
import com.kele.utils.ResponseData;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.ibatis.annotations.Param;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.UUID;

/**
 * 创作人 王箫凯
 * Date 2021/5/24
 * Time 14:30
 * @author 王箫凯
 */

@Api(value = "头像上传",tags = "头像上传测试")
@RestController
@RequestMapping(value = "/file")

public class FileController {
    @Resource
    private FileService fileService;

    @ApiOperation(value = "基本",notes = "进行")
    @ResponseBody
    @RequestMapping(value = "/upLoad",method = RequestMethod.POST)
    public ResponseData upLoad(HttpServletRequest request , @RequestParam(value = "upload",required = false) MultipartFile upload) throws Exception {
        //获取文件的类型
        String type ="user";
        //设置文件上传的路径
        String path=request.getSession().getServletContext().getRealPath("static_resources")+"/upload/"+type;

        //获取文件名称
        String filename = upload.getOriginalFilename();
        //获取文件的后缀名：
        String suffix=filename.substring(filename.lastIndexOf("."));
        //组合新的文件ID
        String newName=UUID.randomUUID().toString().replaceAll("-","")+suffix;
        File file=new File(path);
        //如果文件路径不存在，就创建一个新的文件路径
        if (!file.exists()){
            file.mkdirs();
        }
        //文件写入
        // 将读取到的文件写入到路径为path 的newName文件中
        upload.transferTo(new File(path,newName));


        //获取session  从Session中获取此时的用户对象
        User user= (User) request.getSession().getAttribute("User");
        System.out.println("============"+user);
        String account= user.getAccount();

        //调用方法，将信息上传到数据库中
        path="/static_resources/upload/"+type;
        String thePath=path+"/"+newName;
        int nums= fileService.upLoad(thePath,account);
        System.out.println(nums);
        if(nums!=1){
            return ResponseData.fail("错误，上传失败");
        }else {
            user.setSrc(thePath);
            request.getSession().setAttribute("User",user);
            return ResponseData.success("上传成功");
        }
    }
}